package com.yunzheng.studyLeaveSystem.modules.user.leaveFunction.leaveRecord.dao;

import com.yunzheng.studyLeaveSystem.modules.user.leaveFunction.leave.entity.Leave;
import com.yunzheng.studyLeaveSystem.utils.DBUtils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

public class LeaveRecordDao {
    /**
     * 查询请假记录
     * 参数：请假人ID
     * @return 返回：请假记录的集合
     */
    public List<Leave> record(int id){
        Connection con = null;
        PreparedStatement psm = null;
        ResultSet rs = null;
        con = DBUtils.getCon();
        String sql = "select * from leaver where id = ? and YEARWEEK(date_format(leave_date,'%Y-%m-%d')) = YEARWEEK(now())";
        List<Leave> record = null;
        try {
            psm = con.prepareStatement(sql);
            psm.setInt(1,id);
            rs = psm.executeQuery();
            record = new ArrayList<>();
            while (rs.next()){
                String name = rs.getString(1);
                String gender = rs.getString(2);
                String term = rs.getString(3);
                String direction = rs.getString(4);
                String leave_date = rs.getString(5);
                String leave_class = rs.getString(6);
                String reason = rs.getString(7);
                record.add(new Leave(name,term,gender,direction,leave_date,leave_class,reason));
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                DBUtils.release(rs,psm,con);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return record;
    }

    /**
     * 查看请假次数
     * 参数：请假人id
     * @return 返回：请假次数
     */
    public int account(int id){
        Connection con = null;
        PreparedStatement psm = null;
        ResultSet rs = null;
        int leaveAccount = 0;
        try {
            con = DBUtils.getCon();
            String sql = "select count(*) as leaveAccount from leaver where id = ? and YEARWEEK(date_format(leave_date,'%Y-%m-%d')) = YEARWEEK(now())";
            psm = con.prepareStatement(sql);
            psm.setInt(1,id);
            rs = psm.executeQuery();
            while (rs.next()){
                leaveAccount = rs.getInt("leaveAccount");
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }finally {
            try {
                DBUtils.release(rs,psm,con);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }
        return leaveAccount;
    }
}